import React, { useState, useEffect, useRef } from 'react'
import { Popconfirm, Button, Modal, Form, Input } from 'antd';
import { connect } from 'dva';
import { ProTable } from '@ant-design/pro-components';

const ClassifyManage = ({ classifyList, dispatch }) => {
  useEffect(() => {
    tableRef.current?.reload()// 刷新表格
  }, [classifyList])
  const tableRef = useRef();
  const addForm = useRef();
  const [isModal, setIsModal] = useState(false)// 控制弹窗显与隐
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [editForm] = Form.useForm();
  const [formData, setFormData] = useState({})
  const columns = [
    {
      title: '分类id', dataIndex: 'categoryId', key: 'categoryId', align: 'center', search: false,
      sorter: (a, b) => a.categoryId - b.categoryId,
    },
    { title: '分类名称', dataIndex: 'categoryName', key: 'categoryName', align: 'center', },
    { title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center', },
    {
      title: '操作', key: 'classifyInfo', align: 'center', search: false,
      render: (_, data) => {
        return (
          <>
            <Button key={'editClassify'} type='link' onClick={() => handleFormCategory(data)}>编辑</Button>
            <Popconfirm title="确定要删除该标签吗？"
              onConfirm={() => {
                dispatch({
                  type: 'classifyManage/delCategory',
                  payload: {
                    categoryId: data.categoryId,
                  },
                })
              }} okText="确定" cancelText="取消">
              {/* danger 表示红色突出 
                  type='link' 不显示边框
              */}
              <Button danger type='link' key ="delete">删除</Button>
            </Popconfirm>
          </>
        );
      }
    },
  ];

  const addCategory = (data) => {
    handleAddCategory();
    dispatch({
      type: 'classifyManage/addCategory',
      payload: {
        ...data,
      }
    })
    setIsModal(false)
  }

  const handleAddCategory = () => {
    setIsModal(false)
    setFormData({})
    addForm?.current?.resetFields()
  }

  const handleFormCategory = (data) => {
    setIsModalOpen(true);
    editForm?.setFieldsValue(data);
    setFormData(data)
  }
  const updateCategory = (data) => {
    dispatch({
      type: 'classifyManage/updateCategory',
      payload: {
        categoryId: formData.categoryId,
        categoryName: data.categoryName,
      },
    });
    setIsModalOpen(false)
  }

  const reloadTable = () => {
    dispatch({
      type: 'classifyManage/queryCategory',
    })
  }

  return <>
    <ProTable actionRef={tableRef} defaultData={classifyList} columns={columns} rowKey="classifyList"
      toolBarRender={() => [<Button type="primary" onClick={() => { setIsModal(true) }}>新建</Button>]}
      pagination={{
        defaultPageSize: 10, // 默认每页显示10条数据
        showSizeChanger: true, // 显示每页显示条数的选择器
        pageSizeOptions: ['10', '20', '50'], // 可供用户选择的每页显示条数选项
      }}
      options={{ reload: reloadTable, setting: true, density: true, }}
      request={(params, sort, filter) => {
        return Promise.resolve({
          data: () => {
            return classifyList?.filter((item) => {
              let result = true;
              Object.entries(params).forEach(([key, value]) => {
                if (key == "current" || key == "pageSize") {
                  return;
                }
                const dataKey = key.replace("search", "")
                if (item.hasOwnProperty(dataKey)) {
                  result = (result && item[dataKey].indexOf(value) != -1)
                }
              })
              return result;
            });
          },
          success: true,
        });
      }} />;
    <Modal key="editClassify" title="编辑" open={isModalOpen} onCancel={() => setIsModalOpen(false)} maskClosable={false}
      footer={[
        <Button key="back" onClick={() => setIsModalOpen(false)}>取消</Button>,
        <Button key="submit" type="primary" onClick={() => editForm?.submit()}>确定</Button>,
      ]}>
      <Form form={editForm} name="basic" labelCol={{ span: 8, }}
        wrapperCol={{ span: 16, }} style={{ width: "60%" }} onFinish={updateCategory}>
        <Form.Item label="分类名称:" name="categoryName" rules={[
          {
            required: true,
            message: '请输入你想要修改的分类名称!',
          },
          {
            pattern: /^[\u4e00-\u9fa5A-Za-z0-9]+$/,
            message: '分类名称不可用',
          },
          {
            pattern: /^.{1,30}$/,
            message: '分类长度为1-30位!',
          }
        ]}>
          <Input /></Form.Item>
      </Form>
    </Modal>
    <Modal key="addClassify" title="新增" open={isModal} onCancel={() => { handleFormCategory(); }} maskClosable={false}
      footer={[
        <Button key="submit" type="primary" onClick={() => addForm.current?.submit()}>确定</Button>,
        <Button key="back" onClick={() => { handleAddCategory(); }}>取消</Button>,
      ]}>
      <Form ref={addForm} name="basic" labelCol={{ span: 6, }} wrapperCol={{ span: 16, }} onFinish={addCategory}>
        <Form.Item label="分类名称:" name="categoryName" rules={[
          {
            required: true,
            message: '请输入你想要添加的分类名称!',
          },
          {
            pattern: /^[\u4e00-\u9fa5A-Za-z0-9]+$/,
            message: '分类名称不可用',
          },
          {
            pattern: /^.{2,30}$/,
            message: '标签长度为1-30位!',
          }
        ]}>
          <Input /></Form.Item>
      </Form>
    </Modal>{
    }
  </>
}

export default connect(({ classifyManage }) => ({
  classifyList: classifyManage.classifyList,
}))(ClassifyManage);